import os
import tempfile
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.colors import black, blue


class EmergencyPlanPDFGenerator:
    def __init__(self):
        self.styles = getSampleStyleSheet()
        self._setup_chinese_font()
    
    def _setup_chinese_font(self):
        """设置中文字体支持"""
        try:
            # 尝试注册系统中文字体
            font_paths = [
                "C:/Windows/Fonts/simsun.ttc",  # Windows 宋体
                "C:/Windows/Fonts/simhei.ttf",  # Windows 黑体
                "/System/Library/Fonts/PingFang.ttc",  # macOS
                "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",  # Linux
            ]
            
            for font_path in font_paths:
                if os.path.exists(font_path):
                    pdfmetrics.registerFont(TTFont('ChineseFont', font_path))
                    break
            else:
                # 如果没有找到中文字体，使用默认字体
                print("警告：未找到中文字体，将使用默认字体")
                return
                
        except Exception as e:
            print(f"字体设置失败: {e}")
            return
    
    def _create_title_style(self):
        """创建标题样式"""
        title_style = ParagraphStyle(
            'CustomTitle',
            parent=self.styles['Heading1'],
            fontSize=18,
            spaceAfter=20,
            alignment=1,  # 居中
            textColor=blue,
        )
        
        # 如果设置了中文字体，使用中文字体
        registered_fonts = pdfmetrics.getRegisteredFontNames()
        if 'ChineseFont' in registered_fonts:
            title_style.fontName = 'ChineseFont'
            
        return title_style
    
    def _create_heading_style(self):
        """创建小标题样式"""
        heading_style = ParagraphStyle(
            'CustomHeading',
            parent=self.styles['Heading2'],
            fontSize=14,
            spaceAfter=12,
            spaceBefore=20,
            textColor=black,
        )
        
        # 如果设置了中文字体，使用中文字体
        registered_fonts = pdfmetrics.getRegisteredFontNames()
        if 'ChineseFont' in registered_fonts:
            heading_style.fontName = 'ChineseFont'
            
        return heading_style
    
    def _create_content_style(self):
        """创建内容样式"""
        content_style = ParagraphStyle(
            'CustomContent',
            parent=self.styles['Normal'],
            fontSize=12,
            spaceAfter=8,
            leading=16,
            textColor=black,
        )
        
        # 如果设置了中文字体，使用中文字体
        registered_fonts = pdfmetrics.getRegisteredFontNames()
        if 'ChineseFont' in registered_fonts:
            content_style.fontName = 'ChineseFont'
            
        return content_style
    
    def generate_pdf(self, event_type: str, event_subtype: str, plan_data: list, output_path: str = None):
        """
        生成应急预案PDF文件
        
        Args:
            event_type: 事件类型
            event_subtype: 事件子类
            plan_data: 预案数据，格式为 [{"field_name": "字段名", "content": "内容"}, ...]
            output_path: 输出文件路径，如果为None则使用临时文件
            
        Returns:
            生成的PDF文件路径
        """
        if output_path is None:
            # 创建临时文件
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
            output_path = temp_file.name
            temp_file.close()
        
        # 创建PDF文档
        doc = SimpleDocTemplate(output_path, pagesize=A4)
        story = []
        
        # 获取样式
        title_style = self._create_title_style()
        heading_style = self._create_heading_style()
        content_style = self._create_content_style()
        
        # 添加主标题
        main_title = f"{event_type} - {event_subtype} 应急预案"
        story.append(Paragraph(main_title, title_style))
        story.append(Spacer(1, 20))
        
        # 添加预案内容
        for item in plan_data:
            field_name = item.get("field_name", "")
            content = item.get("content", "")
            
            # 添加字段标题
            story.append(Paragraph(field_name, heading_style))
            
            # 添加字段内容
            # 处理换行符
            content_lines = content.split('\n')
            for line in content_lines:
                if line.strip():  # 跳过空行
                    story.append(Paragraph(line.strip(), content_style))
            
            story.append(Spacer(1, 10))
        
        # 生成PDF
        doc.build(story)
        
        return output_path
    
    def generate_pdf_bytes(self, event_type: str, event_subtype: str, plan_data: list):
        """
        生成应急预案PDF文件的字节数据
        
        Args:
            event_type: 事件类型
            event_subtype: 事件子类
            plan_data: 预案数据
            
        Returns:
            PDF文件的字节数据
        """
        # 生成临时PDF文件
        temp_path = self.generate_pdf(event_type, event_subtype, plan_data)
        
        # 读取文件内容
        with open(temp_path, 'rb') as f:
            pdf_bytes = f.read()
        
        # 删除临时文件
        try:
            os.unlink(temp_path)
        except:
            pass
        
        return pdf_bytes 